/*----------------------------------------------------------------------------
 * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved.
 * Description: Mpu Module Implementation
 * Author: zhangfanfan
 * Create: 2013-01-01
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific prior written
 * permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *---------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
 * Notice of Export Control Law
 * ===============================================
 * Huawei LiteOS may be subject to applicable export control laws and regulations, which might
 * include those applicable to Huawei LiteOS of U.S. and the country in which you are located.
 * Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such
 * applicable export control laws and regulations.
 *---------------------------------------------------------------------------*/

#include "los_mpu.inc"
#include "los_base.h"
#include "los_typedef.h"

#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif /* __cplusplus */
#endif /* __cplusplus */

#ifdef LOSCFG_KERNEL_MPU

static UINT8 ucRegionNumBeUsed[MPU_MAX_SUPPORT] = {0}; /* 1: Region has already been used.
                                                          0: Region has already been unused*/
/*****************************************************************************
Function   : osGetRegionCapacity
Description: get region capacity
Input      : uwRegionSize : (region size
                            range: MPU_REGION_SIZE_32B ~ MPU_REGION_SIZE_4GB
                            formula: capacity = 1 << (uwRegionSize + 1);)
Return     : Error Information or capacity(unit: byte)
*****************************************************************************/
static UINT64 osGetRegionCapacity(UINT32 uwRegionSize)
{
    UINT64 uwCapacity;
    const UINT64 SIZE_4G = 4294967296ULL;
    const UINT64 SIZE_2G = 2147483648ULL;

    if(uwRegionSize == MPU_REGION_SIZE_4GB)
    {
        return SIZE_4G;
    }
    else if(uwRegionSize == MPU_REGION_SIZE_2GB)
    {
        return SIZE_2G;
    }

    uwCapacity = 1 << (uwRegionSize + 1);/*lint !e647*/

    return uwCapacity;
}

/*****************************************************************************
Function   : osCheckParame
Description: check parame
Input      : pstMpuInfo: MPU info
Return     : Error Information or LOS_OK
*****************************************************************************/
static UINT32 osCheckParame(MPU_REGION_INFO *pstMpuInfo)
{
    UINT64 uwCapacity;

    if(NULL == pstMpuInfo)
    {
        return LOS_ERRNO_MPU_PTR_NULL;
    }

    /* Judge whether the chip with MPU */
    if(MPU->TYPE == 0)
    {
        return LOS_ERRNO_MPU_NOT_CONFIGURED;
    }

    /* Number exceeds the maximum value supported by MPU */
    if(pstMpuInfo->ucNumber > MPU_MAX_SUPPORT - 1)
    {
        return LOS_ERRNO_MPU_INVALID_NUMBER;
    }

    /* Selected number region has been enabled */
    if(ucRegionNumBeUsed[pstMpuInfo->ucNumber])
    {
        return LOS_ERRNO_MPU_REGION_IS_ENABLED;
    }

    if((pstMpuInfo->uwRegionSize < MPU_REGION_SIZE_32B) || (pstMpuInfo->uwRegionSize > MPU_REGION_SIZE_4GB))
    {
        return LOS_ERRNO_MPU_INVALID_CAPACITY;
    }

    uwCapacity = osGetRegionCapacity(pstMpuInfo->uwRegionSize);
    /* Base address is not in the range of RAM */
    if(pstMpuInfo->uwBaseAddress < MPU_MIN_RAM_ADDRESS || pstMpuInfo->uwBaseAddress > MPU_MAX_RAM_ADDRESS)
    {
        return LOS_ERRNO_MPU_BASE_ADDRESS_NOT_IN_RAM;
    }

    /* Input capacity exceeds available space */
    if((MPU_MAX_RAM_ADDRESS - pstMpuInfo->uwBaseAddress) < uwCapacity)
    {
        return LOS_ERRNO_MPU_REGION_SIZE_IS_TOO_BIG;
    }

    if(0 != (pstMpuInfo->uwBaseAddress % uwCapacity))
    {
        return LOS_ERRNO_MPU_INVALID_BASE_ADDRESS;
    }

    if(pstMpuInfo->uwAccessPermission > MPU_DEFS_RASR_AP_RO)
    {
        return LOS_ERRNO_MPU_REGION_INVALID_ACCESS;
    }

    return LOS_OK;
}

/*****************************************************************************
Function   : LOS_RegionDisable
Description: disable region by number
Input      : ucNumber: mpu region number want to disable
Return     : LOS_OK or Error Information
*****************************************************************************/
UINT32 LOS_RegionDisable(UINT8 ucNumber)
{
    UINTPTR uwIntSave;

    if(ucNumber > MPU_MAX_SUPPORT - 1)
    {
        return LOS_ERRNO_MPU_INVALID_NUMBER;
    }

    if(0 == ucRegionNumBeUsed[ucNumber])
    {
        return LOS_ERRNO_MPU_REGION_IS_DISABLED;
    }

    uwIntSave = LOS_IntLock();

    MPU->RNR  = ucNumber;
    MPU->RBAR = 0;
    MPU->RASR = 0;

    ucRegionNumBeUsed[ucNumber] = 0;

    LOS_IntRestore(uwIntSave);

    return LOS_OK;
}

/*****************************************************************************
Function   : osMpuDisable
Description: disable mpu
Input      : NULL
Return     : NULL
*****************************************************************************/
static VOID osMpuDisable(VOID)
{
    /* Make sure outstanding transfers are done */
    __DMB();
    MPU->CTRL = MPU_DISABLE;
}

/*****************************************************************************
Function   : osMpuEnable
Description: enable mpu
Input      : bHfnmiena: Whether in the NMI and hard fault service routine is
                        not mandatory in addition to MPU
Return     : NULL
*****************************************************************************/
static VOID osMpuEnable(BOOL bHfnmiena)
{
     UINT32 enable;

     enable = MPU_CTRL_ENABLE_Msk
            | MPU_CTRL_PRIVDEFENA_Msk
            | bHfnmiena << MPU_CTRL_HFNMIENA_Pos;

     MPU->CTRL = enable;
     /* Ensure MPU settings take effects */
     __DSB();
     /* Sequence instruction fetches using update settings */
     __ISB();
}

/*****************************************************************************
Function   : osMpuRegionConfig
Description: mpu config
Input      : rp: MPU parameters to be set
             The base address must be in the range of RAM
Return     : LOS_OK or Error Information
*****************************************************************************/
static VOID osMpuRegionConfig(MPU_REGION_INFO *pstMpuInfo)
{
    UINT32 uwAttributeAndCapacity;

    uwAttributeAndCapacity = pstMpuInfo->uwAccessPermission << MPU_RASR_AP_Pos
        | pstMpuInfo->bSharable << MPU_RASR_S_Pos
        | pstMpuInfo->bCachable << MPU_RASR_C_Pos
        | pstMpuInfo->bBuffable << MPU_RASR_B_Pos
        | pstMpuInfo->bXN << MPU_RASR_XN_Pos
        | pstMpuInfo->uwRegionSize << MPU_RASR_SIZE_Pos
        | MPU_RASR_ENABLE_Msk;

    MPU->RNR  = pstMpuInfo->ucNumber;
    MPU->RBAR = pstMpuInfo->uwBaseAddress;
    MPU->RASR = uwAttributeAndCapacity;
}

/*****************************************************************************
Function   : LOS_SetProtectionRegion
Description: set protection region
Input      : rp: MPU parameters to be set
             The base address must be in the range of RAM
Return     : LOS_OK or Error Information
*****************************************************************************/
UINT32 LOS_SetProtectionRegion(MPU_REGION_INFO *pstMpuInfo)
{
    UINT32 ret;
    UINTPTR uwIntSave;

    uwIntSave = LOS_IntLock();

    ret = osCheckParame(pstMpuInfo);
    if(LOS_OK != ret)
    {
        LOS_IntRestore(uwIntSave);
        return ret;
    }

    /* Dual word alignment mode enable stack */
    SCB->CCR |= SCB_CCR_STKALIGN_Msk;
    /* enable MemManage fault */
    SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;

    osMpuDisable();
    osMpuRegionConfig(pstMpuInfo);
    osMpuEnable(pstMpuInfo->bHfnmiena);

    ucRegionNumBeUsed[pstMpuInfo->ucNumber] = 1;

    LOS_IntRestore(uwIntSave);

    return LOS_OK;
}

#endif /* LOSCFG_KERNEL_MPU */
#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cplusplus */
#endif /* __cplusplus */

